// 云对象教程: https://uniapp.dcloud.net.cn/uniCloud/cloud-obj
// jsdoc语法提示教程：https://ask.dcloud.net.cn/docs/#//ask.dcloud.net.cn/article/129
let dbJQL;
module.exports = {
	_before: function() { // 通用预处理器
		// this.startTime = Date.now();
		// let body = this.getHttpInfo().body;
		// if(!body) throw result{400,"required"};
		// this.params = JSON.parse(this.getHttpInfo().body);

		if (!this.getUniIdToken()) {
			throw new Error('请重新登录')
		}
		const params = this.params;

		dbJQL = uniCloud.databaseForJQL({ // 获取JQL database引用，此处需要传入云对象的clientInfo
			clientInfo: this.getClientInfo()
		})
		dbJQL.setUser({
			uid: '6651d8f781173e5df6bd55a2',
			role: ['admin']
		})
	},
	/**
	 * method1方法描述
	 * @param {string} param1 参数1描述
	 * @returns {object} 返回值描述
	 */
	/* 
	method1(param1) {
		// 参数校验，如无参数则不需要
		if (!param1) {
			return {
				errCode: 'PARAM_IS_NULL',
				errMsg: '参数不能为空'
			}
		}
		// 业务逻辑
		
		// 返回结果
		return {
			param1 //请根据实际需要返回值
		}
	}
	*/
	async getUserInfo(uid) {

		// const db = uniCloud.database();

		try {
			const reuslt = await dbJQL.collection('uni-id-users').where({
				_id: uid
			}).field('_id,last_login_date,nickname,mobile,avatar,role').get({
				getOne: true
			});

			return reuslt;

		} catch (e) {
			//TODO handle the exception
			return e;
		}

	},
	async getUserAll(){
		const reuslt = await dbJQL.collection('uni-id-users').field('_id,last_login_date,nickname,mobile,avatar,role,register_date').get({getCount:true});
		
		return reuslt;
	},
	async getUserInfoForToken(token) {
	
		// const db = uniCloud.database();
	
		try {
			const reuslt = await dbJQL.collection('uni-id-users').where({
				token: token
			}).field('_id,last_login_date,nickname,mobile,avatar').get({
				getOne: true
			});
	
			return reuslt;
	
		} catch (e) {
			//TODO handle the exception
			return e;
		}
	
	},
	// 更新头像
	async updateAvatar(params) {
		const {
			_id,
			avatarUrl
		} = params;
		const result = await dbJQL.collection('uni-id-users').where({
			_id: _id
		}).update({
			avatar: avatarUrl
		});
		return result;
	},
	// 更新昵称
	async updateNickName(params) {
		const {
			_id,
			nickname
		} = params;
		const result = await dbJQL.collection('uni-id-users').where({
			_id: _id
		}).update({
			nickname: nickname
		});
		return result;
	},
	// 更新手机号
	async updateMobile(user) {
		const {
			_id,
			phoneNumber
		} = user;
		const result = dbJQL.collection('uni-id-users').where({
			_id: _id
		}).update({
			mobile: phoneNumber
		});



		return result;

	}
}